package models;

import com.avaje.ebean.Page;
import org.joda.time.DateTime;
import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.util.Date;
import java.util.List;

@Entity
public class AccountingRow extends Model {

    @Id
    public Long id;

    @Constraints.Required
    public String label;

    @Constraints.Required
    public float amount;

    @ManyToOne
    public Category category;

    public Date date;

    public static Finder<Long, AccountingRow> find = new Finder<Long, AccountingRow>(Long.class, AccountingRow.class);

    public static Page<AccountingRow> page(int page, int pageSize, String sortBy, String order, String filter) {
        return find.where()
                .ilike("label", "%" + filter + "%")
                .orderBy(sortBy + " " + order)
                .findPagingList(pageSize)
                .getPage(page);
    }

    public static List<AccountingRow> month(int year, int month) {
        return month(year, month, null);
    }

    public static List<AccountingRow> month(int year, int month, Category category) {
        return fromTo(year, month, 0, category);
    }

    public static List<AccountingRow> fromJanuary(int year, int month, Category category) {
        return fromTo(year, 1, month, category);
    }

    public static List<AccountingRow> fromTo(int year, int startMonth, int endMonth, Category category) {
        if(startMonth == 0){
            return null;
        }
        if(endMonth == 0){
            endMonth = startMonth;
        }
        DateTime firstDayOfMonth = new DateTime(year, startMonth, 1, 0, 0);
        DateTime lastDayOfMonth = new DateTime((endMonth < 12 ) ? year : year + 1, (endMonth < 12 ) ? endMonth + 1 : 1, 1, 0, 0);
        List<AccountingRow> accountingRows = null;
        if (category == null) {
            accountingRows = find.where()
                    .between("date", firstDayOfMonth, lastDayOfMonth)
                    .orderBy("date ASC")
                    .findList();
        } else {
            accountingRows = find.where()
                    .eq("category", category)
                    .between("date", firstDayOfMonth, lastDayOfMonth)
                    .orderBy("date ASC")
                    .findList();
        }
        return accountingRows;
    }
}
